<?php
/**
 * Note: role_access 缓存类
 * Date: 2020/3/26
 */
namespace App\Caches;

use App\Models\RoleAccess;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;

class RoleAccessCache
{
    const CACHE_KEY = 'role_access';

    /**
     * 处理后的数据
     * @return array
     */
    private static function handleData()
    {
        return RoleAccess::select(['id', 'route'])->get()->toArray();
    }

    /**
     * @return bool
     */
    public static function set()
    {
        return Cache::put(self::CACHE_KEY, self::handleData());
    }

    /**
     * @return mixed
     */
    public static function get()
    {
        $instance = new self();
        return Cache::rememberForever(self::CACHE_KEY, function() use ($instance) {
            return $instance::handleData();
        });
    }

    /**
     * @return bool
     */
    public static function del()
    {
        return Cache::forget(self::CACHE_KEY);
    }

    /**
     * 检测路由是否存在
     * @param string $route
     * @return bool
     */
    public static function routeExists(string $route)
    {
        $all = self::get();
        return in_array($route, Arr::pluck($all, 'route'));
    }

    /**
     * @param $id
     * @return mixed
     */
    public static function first($id)
    {
        $all = self::get();
        return Arr::first($all, function($val, $key) use ($id) {
            return $val['id'] === $id;
        });
    }

    /**
     * 重置缓存
     * @return bool
     */
    public static function reset()
    {
        return self::set();
    }
}
